//task_filterMaintenance.js
var tDate = require("../../utils/date.js");
const util = require("../../utils/util.js");

const app = getApp()

Page({
  data: {
    order_id: '',
    // 任务时间
    taskTime: "",
    selectedTask_type: "滤网维护",
    // 住宅位置
    taskAddress: "",
    // 机器编号
    materialNo: "",
    // 机器ID
    materialID:"",
    // 出风口数据
    airOutlet: "",
    // 客户建议
    userInfos: "",
    // 备注：
    notes: "",

    // 存放本地图片路径
    tempFilePaths: [],
    // 存放图片上传路径
    imagesUpload: [],
    // 滤网建材
    filterBuildArray: [],
    historyFilterBuildArray: [],
  },
  onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      order_id: options.id,
      taskTime: options.time,
      taskAddress: options.address
    })

    this.refreshNewData();
    console.log("上门安装：id=" + this.data.order_id + 'address=' + this.data.taskAddress + 'time=' + this.data.taskTime);
    // 初始化提示框
    this.$wuxToast = app.wux(this).$wuxToast
  },
  // 出风口数据
  input_airOutlet: function (e) {
    console.log("出风口数据:" + e.detail.value);
    this.setData({
      airOutlet: e.detail.value
    })
  },
  // 客户建议
  input_userInfos: function (e) {
    this.setData({
      userInfos: e.detail.value
    })
  },
  // 备注
  input_notes: function (e) {
    this.setData({
      notes: e.detail.value
    })
  },
  // 查看上传图片
  uploadImageShowAction: function (event) {
    var index = event.currentTarget.dataset.index;
    var that = this;
    var currentUrl = that.data.imagesUpload[index];

    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: that.data.imagesUpload // 需要预览的图片http链接列表
    })
  },
  // 选择图片
  chooseimage: function () {
    var _this = this;
    var imagePaths = this.data.tempFilePaths;
    var uploadImagePaths = this.data.imagesUpload;

    wx.chooseImage({
      count: 9, // 默认9  
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 新选择图片的本地路径
        var filePathsArray = res.tempFilePaths;
        wx.showToast({
          title: '上传中...',
          icon: 'loading',
          mask: true,
          duration: 20000000
        });

        filePathsArray.forEach(function (item, index) {
          wx.uploadFile({
            url: app.globalData.BaseURL + '/fileUpload/image',
            filePath: item,
            name: 'file',
            success: function (res) {
              var state = JSON.parse(res.data).state;
              if (state == "success") {
                var url = JSON.parse(res.data).url;
                // 存放图片上传路径数组加1️
                uploadImagePaths.push(url);
                _this.setData({
                  imagesUpload: uploadImagePaths
                })
                // 存放本地图片路径数组加1️
                imagePaths.push(item);
                _this.setData({
                  tempFilePaths: imagePaths
                })
                if (index == filePathsArray.length - 1) {
                  wx.hideToast();
                }
              } else {
                wx.hideToast();
                _this.$wuxToast.show({
                  type: 'text',
                  timer: 1500,
                  color: '#fff',
                  text: '图片上传失败，请重新选择',
                  success: () => console.log('文本内容')
                })
              }
              console.log("上传成功");
              console.log(JSON.parse(res.data));
              console.log(JSON.parse(res.data).url);
            },
            fail: function (res) {
              wx.hideToast();
              console.log("上传失败：" + res.data);
              _this.$wuxToast.show({
                type: 'text',
                timer: 1500,
                color: '#fff',
                text: '图片上传失败，请重新选择',
                success: () => console.log('文本内容')
              })
            }, complete: function () {

            }
          });
        });

      }
    })
  },
  // 提交表单按钮
  submitInfo: function () {
    var notesStr = this.data.notes;
    var userInfosStr = this.data.userInfos;
    console.log("客户建议：" + userInfosStr);
    var uploadImagesArr = this.data.imagesUpload;

    //刷新数据
    //加载提示框
    util.showLoading();
    var that = this;
    var pages = getCurrentPages()
    // var prevPage = pages[pages.length-1]  //当前界面
    var prevPage = pages[pages.length - 2]  //上一个页面

    // 出风口数据：airOutlet
    console.log("出风口数据：" + this.data.airOutlet);
    var airOutletStr = this.data.airOutlet;

    var urlString = app.globalData.BaseURL + '/api/task/addFilterReport';
    var dataSource = util.json2Form({
      taskId: that.data.order_id,
      remark: notesStr,
      userInfos: userInfosStr,
      airOutlet: airOutletStr,
      uploadImages: uploadImagesArr
    });

    wx.request({
      method: "POST",
      url: urlString,
      data: dataSource,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'adminUserViewId': app.globalData.adminUserViewId,
        'token': app.globalData.token
      },
      success: function (res) {
        util.hideToast();
        console.log("data=====" + res.data);
        var code = res.data.code;
        console.log("code=====" + code);
        if (code === 200) {
          that.$wuxToast.show({
            type: 'text',
            timer: 1000,
            color: '#fff',
            text: '上传成功',
            success: () => console.log('提交成功')
          });
          // 更改前一页面列表页的refreshLish属性，让其出现时刷新页面
          prevPage.setData({
            refreshLish: "true"
          });
          setTimeout(function () {
            wx.navigateBack({});
          }, 1000);
        } else {
          that.$wuxToast.show({
            type: 'text',
            timer: 1000,
            color: '#fff',
            text: res.data.msg,
            success: () => console.log('上传失败，请重新提交。')
          });
        }
      },
      fail: function () {
        that.$wuxToast.show({
          type: 'text',
          timer: 1000,
          color: '#fff',
          text: '网络错误，请稍后重试。',
          success: () => console.log('网络错误，请稍后重试。')
        })
      }, complete: function () {
        util.hideToast();
      }
    })
  },
  // 任务失败跳转
  taskFailedAction: function () {
    var that = this;
    wx.navigateTo({
      url: '/pages/task_failed/task_failed' + '?id=' + that.data.order_id + '&time=' + that.data.taskTime + '&address=' + that.data.taskAddress + '&task_type=' + that.data.selectedTask_type
    })
  },
  // 查看历史维保信息
  lookHistoricalInfoAction: function () {
    var that = this;
    wx.navigateTo({
      url: '/pages/task_filterMaintenance/historyFilterList/historyFilterList' + '?materialID=' + that.data.materialID
    })
  },
  //刷新数据
  refreshNewData: function () {
    //加载提示框
    util.showLoading();
    var that = this;
    var urlStr = '/api/task/' + this.data.order_id;
    var parameters = "";
    console.log("parameters = " + parameters);
    util.request(urlStr, parameters, function (res) {
      util.hideToast();
      console.log("+++++请求成功");
      console.log("data===" + res.data);
      var materialNoStr = res.data.data.machine;
      var materialIDStr = res.data.data.machineId;

      var filterBuildArrayStr = res.data.data.partsList;
      var historyFilterBuildArrayStr = res.data.data.partsHisList;

      that.setData({
        materialNo: materialNoStr,
        materialID: materialIDStr,
        filterBuildArray: filterBuildArrayStr,
        historyFilterBuildArray: historyFilterBuildArrayStr
      });

      var startTime = res.data.data.task.startTime;
      if (startTime == "" || startTime == undefined) {
        // 未开始任务，提示先开始任务
        wx.showModal({
          title: '该任务暂未开始',
          content: '请返回首页开始任务，再提交任务信息',
          cancelText: '暂不开始',
          confirmText: '立即返回',
          success: function (res) {
            if (res.confirm) {
              console.log("确认返回首页");
              wx.navigateBack({})
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }

    })
  }
})